
__author__ = 'mtxrym'

import pymongo
import json
import time
import csv
import math
import matplotlib.pyplot as plt

MONGODB_HOST = "127.0.0.1"
MONGODB_PORT = 27017
TIME_FORMAT = "%a %b %d %H:%M:%S +0000 %Y"
SOURCE_FILE = "/Users/mtxrym/Downloads/filter.txt"
connection = pymongo.Connection(MONGODB_HOST, MONGODB_PORT)
db = connection.timeseries


dict_u = {}

def insert_into_mongo():
    filter = db.filter_n
    file = open(SOURCE_FILE)
    for line in file:
        filter.insert(json.loads(line))


class Series:

    def __init__(self, tid, name, ttime, level):
        self.tid = tid
        self.name = name
        self.ttime = ttime
        self.level = level
        if level == 0:
            self.sample = 3600*24
        elif level == 1:
            self.sample = 3600
        elif level == 2:
            self.sample = 60
        else:
            self.sample = 15*60
        self.series = []


    def get_series(self):
        return self.series
    def __str__(self):
        return self.name + self.tid

    def __repr__(self):
        return self.name + str(self.tid)

    def generate_series(self):
        for retweet in db.filter_n.find({"retweeted_status.id": self.tid}):
            ftime = retweet["created_at"]
            fstime = time.mktime(time.strptime(ftime, TIME_FORMAT))
            disc = int((fstime - self.ttime)/self.sample)
            while  disc >= len(self.series):
                self.series.append(0)
            self.series[disc] += 1
    def plot_series(self):
        plt.plot(self.series)
        plt.ylabel('some numbers')
        plt.show()
    def calculate_a(self):
        a = 0.0
        i = 0
        b = 0.5
        for j in self.series:
            a += math.exp( -1 * i * b) * j
            i += 1
        return a
    def write_to_csv(self):
        with open('egg2.csv', 'a') as csvfile:
            spamwriter = csv.writer(csvfile, dialect='excel')
            spamwriter.writerow([self.name, self.ttime, self.tid] + self.series)




def plot_from_file(FILE_NAME):
    plotsrc = {}
    with open(FILE_NAME) as csvfile:
        for line in csvfile:
            [a,b,c] = line.split(",")
            print a,b,c

if __name__ == "__main__":
    # insert_into_mongo()
    # for tweet in db.filter_n.find({"retweeted_status": {"$exists": False}, "in_reply_to_user_id": None,"delete": {"$exists": False}}):
    #     ttime = tweet["created_at"]
    #     tid = tweet["id"]
    #     name = tweet["user"]["screen_name"]
    #     stime = time.mktime(time.strptime(ttime, TIME_FORMAT))
    #
    #     s = Series(tid, name, stime, 1)
    #     s.generate_series()
    #     if name not in dict_u.keys():
    #         dict_u[name] = []
    #     dict_u[name].append(s)
    # print dict_u
    # for item in dict_u:
    #     for h in dict_u[item]:
    #         plt.plot(h.series)
    #     plt.show()
        # s.plot_series()

        # print s.calculate_a()
        # s.write_to_csv()
    plot_from_file("/Users/mtxrym/egg.csv");